package cn.seaboot.commons.ftp.pool;

import cn.seaboot.commons.ftp.DataSource;
import cn.seaboot.commons.ftp.Ftp;
import cn.seaboot.commons.ftp.FtpProperties;
import org.apache.commons.net.ftp.FTPClient;

import java.io.IOException;

/**
 * 一个受连接池管理的 DataSource
 *
 * @author Mr.css
 * @version 2021-02-20 11:04
 */
public class FtpPooledSource implements AutoCloseable, DataSource {

    /**
     * FTP参数
     */
    private final FtpProperties ftpProperties;

    /**
     * Ftp连接池
     */
    private final FTPClientPool ftpClientPool;

    public FtpPooledSource(FtpProperties ftpProperties) {
        this.ftpProperties = ftpProperties;
        PooledFTPClientFactory ftpFactory = new PooledFTPClientFactory(ftpProperties);
        this.ftpClientPool = new FTPClientPool(ftpFactory, ftpProperties);
    }

    /**
     * 返回一个受连接池管理的 Ftp 连接
     *
     * @return FtpCommand
     */
    @Override
    public Ftp build() {
        return new Ftp(this, this.ftpProperties);
    }

    /**
     * 关闭一个FTP连接，重置作业空间，退回连接池
     *
     * @param ftp -
     */
    @Override
    public void closeFtp(Ftp ftp) {
        try {
            ftp.changeToRootDirectory();
            ftpClientPool.returnFTPClient(ftp.getFtpClient());
        } catch (IOException ignore) {
        }
    }

    /**
     * 通过连接池，对外借出一个FTPClient
     *
     * @return -
     */
    @Override
    public FTPClient createFTPClient() {
        return ftpClientPool.borrowFTPClient();
    }


    /**
     * 销毁当前对象，连接池销毁
     */
    @Override
    public void close() {
        ftpClientPool.close();
    }
}
